package com.selfdiscipline.ui.screens.habit

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.data.local.entity.HabitEntity
import com.selfdiscipline.domain.repository.HabitRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.LocalDate
import javax.inject.Inject

@HiltViewModel
class HabitViewModel @Inject constructor(
    private val habitRepository: HabitRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(HabitUiState())
    val uiState: StateFlow<HabitUiState> = _uiState.asStateFlow()

    init {
        loadHabits()
        calculateCurrentStreak()
    }

    fun completeHabit(habitId: Long) {
        viewModelScope.launch {
            val habit = habitRepository.getHabitById(habitId) ?: return@launch
            val today = LocalDate.now()
            
            // 只有今天还没完成的习惯才能标记为完成
            if (habit.lastCompletedDate != today) {
                habitRepository.completeHabit(habitId, today)
                loadHabits()
                calculateCurrentStreak()
            }
        }
    }
    
    private fun loadHabits() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            
            habitRepository.getActiveHabits().collect { habits ->
                _uiState.update { 
                    it.copy(
                        habits = habits,
                        isLoading = false
                    )
                }
            }
        }
    }
    
    private fun calculateCurrentStreak() {
        viewModelScope.launch {
            val maxStreak = habitRepository.getMaxStreak() ?: 0
            _uiState.update { it.copy(currentStreak = maxStreak) }
        }
    }
}

data class HabitUiState(
    val isLoading: Boolean = true,
    val habits: List<HabitEntity> = emptyList(),
    val currentStreak: Int = 0,
    val error: String? = null
) 